<template>
  <q-input
    v-model="json"
    type="textarea"
    :rows="12"
    placeholder="仅支持JSON格式"
    :disabled="disabled"
  />
</template>

<script setup>
import { ref } from '@vue/composition-api';

const props = defineProps({
  dataIds: {
    type: Array,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: false
  }
});

const json = ref('');

const validate = () => {
  let data;
  try {
    data = JSON.parse(json.value);
  } catch (err) {
    console.log(err);
    return false;
  }
  if (typeof data !== 'object') {
    return false;
  }
  return true;
};

const getValues = () => {
  const data = JSON.parse(json.value);
  if (Array.isArray(data)) {
    data.forEach((item, index) => {
      props.dataIds.forEach(key => {
        item[key] = index + 1;
      });
    });
  }

  return data;
};

const setValues = (data) => {
  json.value = JSON.stringify(data, null, 2);
};

defineExpose({
  setValues,
  getValues,
  validate
});
</script>
